package com.example.udp;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;



public class MainActivity extends AppCompatActivity {
    EditText etip,etreceiveport,etzhenceport,etmess;
    Button btnok,btnsend;
    TextView tvshow;
    InetAddress inetaddress = null;
    DatagramPacket pack;
    DatagramSocket sendsocket=null,receivesocket=null;
    Message m;
    String ip;
    int receiveport,zhenceport;

    static final int RECEIVE_WHAT=1,SEND_WHAT=2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        btnok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ip = etip.getText().toString();
                receiveport = Integer.parseInt(etreceiveport.getText().toString());
                zhenceport = Integer.parseInt(etzhenceport.getText().toString());
                new Thread(new ReceiveMessage()).start();
            }
        });
        btnsend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new SendMessage()).start();
            }
        });
    }


    public void initView()
    {
        etip = (EditText)findViewById(R.id.et_ip);
        etreceiveport = (EditText)findViewById(R.id.et_port);
        etzhenceport = (EditText)findViewById(R.id.et_zhenceport);
        etmess = (EditText)findViewById(R.id.et_mess);
        btnok = (Button)findViewById(R.id.btn_ok);
        btnsend = (Button)findViewById(R.id.btn_send);

        tvshow = (TextView)findViewById(R.id.tv_show);
        tvshow.setMovementMethod(ScrollingMovementMethod.getInstance());

    }

//    tvshow.post(new Runnable() {
//        public void run() {
//            tvshow.append(showString);
//            int scrollAmount = tvshow.getLayout().getLineTop(tvshow.getLineCount()) - tvshow.getHeight();
//            if (scrollAmount > 0)
//                tvshow.scrollTo(0, scrollAmount);
//            else
//                tvshow.scrollTo(0, 0);
//        }
//    });



    public class SendMessage implements Runnable{

        @Override
        public void run() {
            String sendmessage = etmess.getText().toString();


            byte[] buffer = sendmessage.getBytes();
            try {

                inetaddress = InetAddress.getByName(ip);
                pack = new DatagramPacket(buffer,buffer.length,inetaddress,receiveport);
                sendsocket = new DatagramSocket();
                sendsocket.send(pack);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            catch (SocketException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            Bundle bundle = new Bundle();
            bundle.putString("send",sendmessage);
            m = new Message();
            m.what = SEND_WHAT;
            m.setData(bundle);

            handler.sendMessage(m);
            sendsocket.close();

        }
    }


    public class ReceiveMessage implements Runnable{
        byte data[] = new byte[8192];
        String message = null,str;

        @Override
        public void run() {
            pack = new DatagramPacket(data,data.length);
            try {
                receivesocket = new DatagramSocket(null);
                receivesocket.setReuseAddress(true);
                receivesocket.bind(new InetSocketAddress(zhenceport));
            } catch (SocketException e) {
                e.printStackTrace();
            }
            do
            {
                try {
                    receivesocket.receive(pack);
                    message = new String(pack.getData(),0,pack.getLength());
                    str = pack.getAddress().getHostAddress();
                    m = new Message();
                    m.what=RECEIVE_WHAT;

                    Bundle bundle = new Bundle();
                    bundle.putString("receiveip",str);
                    bundle.putString("receivedata",message);
                    m.setData(bundle);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    handler.sendMessage(m);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }while(!"quit".equalsIgnoreCase(message));
            receivesocket.close();
        }
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case RECEIVE_WHAT:
                     tvshow.append("收到"+msg.getData().getString("receiveip")+"的消息："+
                            msg.getData().getString("receivedata")+"\n");
                    break;
                case SEND_WHAT:
                    tvshow.append("发送的消息："+msg.getData().getString("send").toString()+"\n");
                    //etmess.setText("");
                    break;
            }
        }
    };


}
